package com.caifu.controller.elderlyResidents;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.enums.SexTypeEnum;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.ElderlyInfoService;
import com.caifu.util.Util;
import com.caifu.vo.ElderlyInfoAddVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ClassName : ImportElderlyInfoController
 *
 * @author :
 * @description ： 坑爹的产品负责人 坑爹的项目负责人
 * @date : 2020-12-16 10:04
 */
@Controller
@RequestMapping("/importElderlyInfo")
public class ImportElderlyInfoController {

    @Resource
    private ElderlyInfoService elderlyInfoService;


    @Resource
    private YlBuildingMapper ylBuildingMapper;
    @Resource
    private YsLabelMapper ysLabelMapper;
    @Resource
    private YlStaffInfoMapper ylStaffInfoMapper;
    @Resource
    private YlCostMapper ylCostMapper;
    @Resource
    private YlFloorMapper ylFloorMapper;
    @Resource
    private YlRoomMapper ylRoomMapper;
    @Resource
    private YlBedMapper ylBedMapper;


    /**
     * 导入
     *
     * @return Result
     */
    @GetMapping(value = "importReport")
    @ResponseBody
    public Result<Object> importReport() {
        try {
//            DELETE FROM user_info_contact where user_info_contact.user_no in (SELECT USER_NO from yl_elderly_info)
//
//            DELETE from yl_elderly_info
//            DELETE from yl_nursing_record
//            DELETE from yl_assessment_record
//            DELETE from yl_contract_info
//            UPDATE yl_bed set BED_EMPTY=0 where BED_EMPTY='1'

            //敬老院编号
            String pensionNo = "1295";

            File file = new File("C:\\Users\\hml\\Desktop\\1 (2).xlsx");
            List<ImportElderlyInfoExcelVO> excelInfoList = new ArrayList<>();
            EasyExcel.read(file, ImportElderlyInfoExcelVO.class, new AnalysisEventListener<ImportElderlyInfoExcelVO>() {
                @Override
                public void invoke(ImportElderlyInfoExcelVO userInfoExcel, AnalysisContext analysisContext) {
                    excelInfoList.add(userInfoExcel);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();

            //处理数据
            dealExcel(excelInfoList,pensionNo);
            return ResultUtil.success();

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void dealExcel(List<ImportElderlyInfoExcelVO> excelInfoList,String pensionNo) {

        excelInfoList.forEach(model -> {

            ElderlyInfoAddVO elderlyInfoAddVO = new ElderlyInfoAddVO();
            BeanUtils.copyProperties(model, elderlyInfoAddVO);
            //数据转换
            dataConvert(elderlyInfoAddVO);

            //获得床位记录
            YlBedRecord bedRecord = getBedRecord(model, pensionNo);
            //合同
            YlContractInfo contractInfo = getYlContractInfo(model.getStartDate(), model.getEndDate());
            //护理记录
            YlNursingRecord nursingRecord = getYlNursingRecord(model.getNursingCostName(), model.getEffectDate(), model.getStaffName(), pensionNo);
            //长护险
            YlAssessmentRecord assessmentRecord = getYlAssessmentRecord(model.getAssessmentCostName(), model.getValidDate(), pensionNo);
            //联系人
            List<UserInfoContact> contactList = getEmergencyContact(model);

            //放入各种合同
            elderlyInfoAddVO.setYlBedRecord(bedRecord);
            elderlyInfoAddVO.setYlContractInfo(contractInfo);
            elderlyInfoAddVO.setYlNursingRecord(nursingRecord);
            elderlyInfoAddVO.setYlAssessmentRecord(assessmentRecord);
            elderlyInfoAddVO.setUserInfoContactList(contactList);

            try {
                elderlyInfoAddVO.setPensionNo(pensionNo);
                elderlyInfoAddVO.setTellerNo("1");
                elderlyInfoService.saveYlElderlyInfo(elderlyInfoAddVO);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }


        });


    }


    /**
     * 获得床位记录
     */
    private YlBedRecord getBedRecord(ImportElderlyInfoExcelVO vo, String pension) {
        YlBuilding building = getBuildingByName(vo.getBuildingName(), pension);
        YlFloor floor = getFloorByName(vo.getFloorName(), building.getBuildingNo() + "");
        YlRoom room = getRoomByName(vo.getRoomName(), floor.getFloorNo() + "");
        YlBed bed = getBedByName(vo.getBedName(), room.getRoomNo() + "");
        YlCost cost = getYlCost(vo.getBedFeeType() + "", null, "101", pension);
        YlBedRecord ylBedRecord = new YlBedRecord();
        ylBedRecord.setBuildingNo(building.getBuildingNo() + "");
        ylBedRecord.setFloorNo(floor.getFloorNo() + "");
        ylBedRecord.setRoomNo(room.getRoomNo() + "");
        ylBedRecord.setBedNo(bed.getBedNo() + "");
        ylBedRecord.setBedFeeType(cost.getCostNo() + "");
        return ylBedRecord;
    }

    /**
     * 合同
     *
     * @param startDate startDate
     * @param endDate   endDate
     * @return YlContractInfo
     */
    private YlContractInfo getYlContractInfo(String startDate, String endDate) {
        YlContractInfo ylContractInfo = new YlContractInfo();
        ylContractInfo.setStartDate(startDate);
        ylContractInfo.setEndDate(endDate);
        return ylContractInfo;
    }

    /**
     * 护理记录
     *
     * @return YlNursingRecord
     */
    private YlNursingRecord getYlNursingRecord(String nursingCostName, String effectDate, String staffName, String pensionNo) {
        YlCost cost = getYlCost(null, nursingCostName, "102", pensionNo);
        YlStaffInfo staffInfo = getStaffInfo(staffName, pensionNo);
        YlNursingRecord ylNursingRecord = new YlNursingRecord();
        ylNursingRecord.setEffectDate(effectDate);
        ylNursingRecord.setCostNo(cost.getCostNo() + "");
        ylNursingRecord.setStaffNo(staffInfo.getStaffNo() + "");
        return ylNursingRecord;
    }

    /**
     * 长护险
     *
     * @return YlAssessmentRecord
     */
    private YlAssessmentRecord getYlAssessmentRecord(String assessmentCostName, String validDate, String pensionNo) {
        YlCost cost = getYlCost(null, assessmentCostName, "103", pensionNo);
        YlAssessmentRecord ylAssessmentRecord = new YlAssessmentRecord();
        ylAssessmentRecord.setValidDate(validDate);
        ylAssessmentRecord.setCostNo(cost.getCostNo() + "");
        return ylAssessmentRecord;
    }


    /**
     * 从Excel中 获取紧急联系人
     *
     * @param vo vo
     */
    private List<UserInfoContact> getEmergencyContact(ImportElderlyInfoExcelVO vo) {
        //第一联系人
        UserInfoContact oneContact = getUserInfoContactOfExcel(vo.getOneContractName(), vo.getOneMobile());
        //第二联系人
        UserInfoContact twoContact = getUserInfoContactOfExcel(vo.getTwoContractName(),  vo.getTwoMobile());
        //第三联系人
        UserInfoContact threeContact = getUserInfoContactOfExcel(vo.getThreeContractName(), vo.getThreeMobile());
        //第四联系人
        UserInfoContact fourContact = getUserInfoContactOfExcel(vo.getFourContractName(), vo.getFourMobile());

        List<UserInfoContact> userInfoContacts = new ArrayList<>();
        if (Util.isNotNull(oneContact)) {
            userInfoContacts.add(oneContact);
        }
        if (Util.isNotNull(twoContact)) {
            userInfoContacts.add(twoContact);
        }
        if (Util.isNotNull(threeContact)) {
            userInfoContacts.add(threeContact);
        }
        if (Util.isNotNull(fourContact)) {
            userInfoContacts.add(fourContact);
        }
        return userInfoContacts;
    }


    private YlBuilding getBuildingByName(String buildingName, String pensionNo) {
        QueryWrapper<YlBuilding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUILDING_NAME", buildingName);
        queryWrapper.eq("PENSION_NO", pensionNo);
        queryWrapper.eq("BUILDING_STATE", "1");
        return ylBuildingMapper.selectOne(queryWrapper);
    }

    private YlFloor getFloorByName(String floorName, String buildingNo) {
        QueryWrapper<YlFloor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUILDING_NO", buildingNo);
        queryWrapper.eq("FLOOR_NAME", floorName);
        queryWrapper.eq("FLOOR_STATE", "1");
        return ylFloorMapper.selectOne(queryWrapper);
    }


    private YlRoom getRoomByName(String roomName, String floorNo) {
        QueryWrapper<YlRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("FLOOR_NO", floorNo);
        queryWrapper.eq("ROOM_NAME", roomName);
        queryWrapper.eq("ROOM_STATE", "1");
        return ylRoomMapper.selectOne(queryWrapper);
    }

    private YlBed getBedByName(String bedName, String roomNo) {
        QueryWrapper<YlBed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BED_NAME", bedName);
        queryWrapper.eq("ROOM_NO", roomNo);
        //床位是否为空 0：空置 1：已使用 2：已预订
        queryWrapper.eq("BED_EMPTY", "0");
        queryWrapper.eq("BED_STATE", "1");
        return ylBedMapper.selectOne(queryWrapper);
    }

    private YlCost getYlCost(String bedFeeType, String costName, String costType, String pensionNo) {
        //费用类别 101:床位费 102护理费 103 长护险费 104：伙食费
        QueryWrapper<YlCost> queryWrapper = new QueryWrapper<>();
        if (Util.isNotNull(bedFeeType)) {
            queryWrapper.eq("COST_PRICE", bedFeeType);
        }
        if (Util.isNotNull(costName)) {
            queryWrapper.eq("COST_NAME", costName);
        }
        queryWrapper.eq("COST_TYPE", costType);
        queryWrapper.eq("STATUS", "1");
        queryWrapper.eq("PENSION_NO", pensionNo);
        return ylCostMapper.selectOne(queryWrapper);
    }

    private YlStaffInfo getStaffInfo(String staffName, String pensionNo) {
        QueryWrapper<YlStaffInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STAFF_NAME", staffName);
        queryWrapper.eq("PENSION_NO", pensionNo);
        return ylStaffInfoMapper.selectOne(queryWrapper);
    }

    private YsLabel getYsLabelByName(String name) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_name", name);
        queryWrapper.eq("status", "1");
        return ysLabelMapper.selectOne(queryWrapper);
    }


    /**
     * @param contactName  联系人姓名
     * @param mobile       手机电话
     */
    private UserInfoContact getUserInfoContactOfExcel(String contactName, String mobile) {
        if (Util.isNotNull(mobile)) {
            UserInfoContact userInfoContact = new UserInfoContact();
            userInfoContact.setContactName(contactName);
            userInfoContact.setMobile(mobile);
            userInfoContact.setCreateTime(new Date());
            return userInfoContact;
        } else {
            return null;
        }
    }


    private void dataConvert(ElderlyInfoAddVO vo) {

        //性别
        if (Util.isNotNull(vo.getUserSex())) {
            vo.setUserSex(SexTypeEnum.getEnumKey(vo.getUserSex()));
        }
        //认知   认知情况 0：否 1：是
        if (Util.isNotNull(vo.getCognitionStatus())) {
            String is = "否".equalsIgnoreCase(vo.getCognitionStatus()) ? "0" : "1";
            vo.setCognitionStatus(is);
        }
        //民族
        if (Util.isNotNull(vo.getNation())) {
            YsLabel ysLabel = getYsLabelByName(vo.getNation());
            vo.setNation(ysLabel.getLabelCode());
        }
        //户籍
        if (Util.isNotNull(vo.getHouseholdRegister())) {
            YsLabel ysLabel = getYsLabelByName(vo.getHouseholdRegister());
            vo.setHouseholdRegister(ysLabel.getLabelCode());
        }
        //文化程度
        if (Util.isNotNull(vo.getEducation())) {
            YsLabel ysLabel = getYsLabelByName(vo.getEducation());
            vo.setEducation(ysLabel.getLabelCode());
        }
        //籍贯
//        if (Util.isNotNull(vo.getNativePlace())) {
//            YsLabel ysLabel = getYsLabelByName(vo.getNativePlace());
//            vo.setNativePlace(ysLabel.getLabelCode());
//        }
        //社保类型
        if (Util.isNotNull(vo.getSocialSecurityType())) {
            YsLabel ysLabel = getYsLabelByName(vo.getSocialSecurityType());
            vo.setSocialSecurityType(ysLabel.getLabelCode());
        }

    }


}
